package main

import (
	"strings"
	"time"

	"github.com/fsnotify/fsnotify"
	"github.com/labstack/echo"
	"github.com/tylerb/graceful"
	"shqsoft.cn/pas3ui/base"
	"shqsoft.cn/pas3ui/reports"
	"shqsoft.cn/pas3ui/routers"
)

func startServer() {
	e := echo.New()
	routers.SetupMiddlewares(e)
	routers.SetupRoutes(e)
	e.Server.Addr = ":" + base.AppConf.Server.HTTPPort
	err := graceful.ListenAndServe(e.Server, 5*time.Second)
	if err != nil {
		base.Logger.Error(err.Error())
	}
}

func main() {
	watch, err := fsnotify.NewWatcher()
	if err != nil {
		base.Logger.Fatal(err.Error())
	}
	defer watch.Close()
	go func() {
		for {
			select {
			case ev, ok := <-watch.Events:
				if !ok {
					return
				}
				if ev.Op&fsnotify.Write == fsnotify.Write {
					indx := strings.LastIndex(ev.Name, "/")
					name := ev.Name[indx+1 : len(ev.Name)-5]
					reports.DeleteReportCache(name)
				}
			case err, ok := <-watch.Errors:
				if !ok {
					return
				}
				base.Logger.Error(err.Error())
			}
		}
	}()
	path, err := base.WorkPath()
	if err != nil {
		return
	}
	path = path + "/reportConfig"
	err = watch.Add(path)
	if err != nil {
		base.Logger.Fatal(err.Error())
	}
	base.Logger.Info("开始监控reportConfig文件夹")
	startServer()
}
